import { wxShare } from "@/utils";
import uuidv1 from "uuid/v1";
import { gbs } from "@/config/index";
import lifeData from "@/db/life"
export default {
  name: "",
  data() {
    return {
      req: {},
      questionReq: {
        ok_num_flag: 0,
        no_num_flag: 0,
        null_num_flag: 0,
        content: ''
      },
      login: false,
      lifeData: [],
      dialogShow: false,
      resultString: '',
      show: true
    };
  },
  methods: {
    toSelect() {
      if (this.login) {
        this.$router.push("/select");
      } else {
        this.$vux.confirm.show({
          title: "提示",
          content: "请进行微信授权",
          onShow() {
            console.log("plugin show");
          },
          onHide() {
            console.log("plugin hide");
          },
          onCancel() {
            console.log("plugin cancel");
          },
          onConfirm() {
            let url = encodeURIComponent(window.location.href);
            window.location.href = `${gbs.wxUrl}?appid=${
              gbs.wxAppId
            }&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=1@connect_redirect=1#wechat_redirect`;
          }
        });
      }
    },
    question() {
      this.$$api_global_question({
        data: JSON.parse(window.localStorage.getItem("reqData")),
        succFn: res => {}
      });
      window.localStorage.setItem("reqData", JSON.stringify(this.req));
    },
    getRequest() {
      var url = location.href.split("?")[1]; //获取url中"?"符后的字串
      if (window.location.href.indexOf("?") == -1) return {};

      var theRequest = new Object();
      if (url.indexOf("=") != -1) {
        var strs = url.split("&");
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
      }
      return theRequest;
    },
    isLogin(cb) {
      let param = this.getRequest();
      this.$$api_global_oauth({
        data: {
          code: param.code
        },
        succFn: res => {
          this.req.openid = res.openid;
          if (res.unionid) this.req.unionid = res.unionid;
          this.req.openid = res.openid;
          this.$vux.toast.text("授权成功！", "top");
          window.localStorage.setItem("user", JSON.stringify(res));
          window.localStorage.setItem("reqData", JSON.stringify(this.req));
          cb();
        }
      });
    },
    shareHandle(){
      this.$$api_global_question({
          data: {
              ...this.req,
              transmit_flag: 1
          },
          noLoading: true
      })
    },
    getData(){
      this.lifeData = lifeData.map((item, index) => {
        let obj = {}
        obj.text = item
        obj.think_do = false
        obj.done_do = false
        obj.idx = index + 1
        return obj
      })
    },
    thinkDo(index){
      if(!window.localStorage.getItem("user")) {
        this.authorTips()
        return
      }
      let think_item = this.lifeData[index].think_do
      let done_item = this.lifeData[index].done_do
      if(!think_item){
        this.lifeData[index].think_do = true
      } else {
        this.lifeData[index].think_do = false
      }
      if(done_item){
        this.lifeData[index].done_do = false
      }
    },
    doneDo(index) {
      if(!window.localStorage.getItem("user")) {
        this.authorTips()
        return
      }
      let done_item = this.lifeData[index].done_do
      let think_item = this.lifeData[index].think_do
      if(!done_item){
        this.lifeData[index].done_do = true
      } else {
        this.lifeData[index].done_do = false
      }
      if(think_item){
        this.lifeData[index].think_do = false
      }
    },
    buildList() {
      if(!window.localStorage.getItem("user")) {
        this.authorTips()
        return
      }
      this.dialogShow = true
    },
    building() {
      
      let list = this.lifeData.map((item, index) => {
        let obj = {} 
        obj.idx = item.index
        if(item.think_do){
          obj.think_do = 1
        } else {
          obj.think_do = ''
        }
        if(item.done_do) {
          obj.done_do = 2
        } else {
          obj.done_do = ''
        }
        if(!obj.think_do && !obj.done_do){
          return `{${index + 1}|${null}}`
        } else {
          return `{${index + 1}|${obj.think_do}${obj.done_do}}`
        }
      })
      this.questionReq.content = list.join(',') + ','
      this.$$api_global_question({
        data: {
            ...this.req,
            ...this.questionReq
        },
        noLoading: true
    })
      this.resultString = list.join(',')
      window.localStorage.setItem('topicList', JSON.stringify(this.lifeData))
      this.$router.push('build')
      
    },
    authorTips () {
      this.$vux.confirm.show({
        title: "提示",
        content: "请进行微信授权",
        onShow() {
          console.log("plugin show");
        },
        onHide() {
          console.log("plugin hide");
        },
        onCancel() {
          console.log("plugin cancel");
        },
        onConfirm() {
          let url = encodeURIComponent(window.location.href);
          window.location.href = `${gbs.wxUrl}?appid=${
            gbs.wxAppId
          }&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=1@connect_redirect=1#wechat_redirect`;
        }
      });
    }, 
    share () {
      wxShare({
        title: "人生清单",
        text: "这66件事，只要完成其中10件，人生就会很圆满。",
        href: "http://app.allclinic.cn/h5/wx/startActivity/#/life/index",
        imgUrl: "http://app.allclinic.cn/h5/wx/scan_drug/static/img/logo.jpg",
        appMessageSuccFn: () => {
          this.shareHandle()
        },
        timeLineSuccFn: () => {
          this.shareHandle()
        }
      });
    }
  },
  mounted() {
    this.share()
    this.getData()
    this.req = {
      user_flag: uuidv1(),
      ip_flag: "192.168.0.1",
      physical_flag: navigator.appVersion,
      record_type: "1",
      record_type_name: document.title,
      total_num_flag: 66,
      source_type: this.$route.query.source_type || ""
    };
    const params = this.getRequest();
    if (params.code) {
      this.isLogin(() => {
        this.login = true;
        this.question();
      });
    } else {
      if (!window.localStorage.getItem("user")) {
        this.login = false;
      } else {
        this.login = true;
        this.question();
      }
    }

    //检测之前有没有授权过
    if(!window.localStorage.getItem("user") && !params.code){
        this.$vux.confirm.show({
          title: "提示",
          content: "请进行微信授权",
          onShow() {
            console.log("plugin show");
          },
          onHide() {
            console.log("plugin hide");
          },
          onCancel() {
            console.log("plugin cancel");
          },
          onConfirm() {
            let url = encodeURIComponent(window.location.href);
            window.location.href = `${gbs.wxUrl}?appid=${
              gbs.wxAppId
            }&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=1@connect_redirect=1#wechat_redirect`;
          }
        });
    }
    
  }
};